//
//  HeadSearchViewAssembly.m
//  MDC
//
//  Created by Kang on 16/7/21.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "HeadSearchViewAssembly.h"
#import "CtrlCodeScan.h"   //二维码页面
#import "SystemInfoController.h"// 扫描获取到的设备详情
#import "EquipmenDetailsViewModel.h" //设备详情连接层
#import "SearchVC.h"

@interface HeadSearchViewAssembly ()<UITextViewDelegate, CtrlCodeScanDelegate,SystemInfoControllerDelegate>
{
    //UIViewController *_controller;
    SearchVC  *_controller;
    BOOL isClearn; //判断内容是否清空
    UIView *keyboardView;
    UITextView *search_textView;
    UIButton *rightSearchBtn;
}

@end

@implementation HeadSearchViewAssembly

- (instancetype)initWithWithViewController:(UIViewController *)vc {
    if (self = [super initWithFrame:vc.navigationController.navigationBar.frame]) {
        [self initWithSearchView];
        _controller = (SearchVC *) vc;
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initWithSearchView];
    }
    return self;
}


- (void)initWithSearchView {
    isClearn = true;
    CGFloat searchView_W = self.frame.size.width;
    CGFloat searchView_X = 4;
    CGFloat searchView_Y = searchView_X;
    
    CGFloat imageView_W = 20;
    UIColor * color =  [UIColor colorWithRed:139/255.0 green:139/255.0 blue:139/255.0 alpha:1.f];
    
    [self setBackgroundColor:[UIColor colorWithRed:26/255.0 green:32/255.0 blue:40/255.0 alpha:1.0]];
    
    // 放大镜
    UIImageView * imageView  = [[UIImageView alloc] initWithFrame:CGRectMake(searchView_X - 2, searchView_Y + 10, imageView_W, imageView_W)];
    [imageView setImage:[UIImage imageNamed:@"icon-sousuo"]];
    [self addSubview:imageView];
    
    
    //二维码
    
//    rightSearchBtn = [[UIButton alloc] initWithFrame:CGRectMake(searchView_W - 2*imageView_W -3, (self.frame.size.height/2) - ((imageView_W)/2) , 48, 48)];
//    
//    rightSearchBtn.backgroundColor = RGB(0, 255, 0, 1);
//    [rightSearchBtn setImage:[UIImage imageNamed:@"icon-QR"] forState:UIControlStateNormal];
//    
//   
//    //rightSearchBtn.frame = CGRectMake(searchView_W - 2*imageView_W -3, (self.frame.size.height/2) - ((imageView_W)/2) , 38, 38);
//    [rightSearchBtn sizeToFit];
//    [self addSubview:rightSearchBtn];
//    [rightSearchBtn addTarget:self action:@selector(showQRCode:) forControlEvents:UIControlEventTouchUpInside];
    

    
    
    //输入框
    search_textView = [[UITextView alloc] initWithFrame:CGRectMake(27,
                                                                           searchView_Y +10,
                                                                           searchView_W - 70,
                                                                           self.frame.size.height - 20)];
    search_textView.backgroundColor = [UIColor clearColor];
    search_textView.delegate  = self;
    search_textView.text = NSLocalizedString(@"搜索", nil);
    search_textView.textColor = [UIColor whiteColor];
    search_textView.returnKeyType = UIReturnKeySearch;
    search_textView.scrollEnabled = NO;
    search_textView.font = [UIFont systemFontOfSize:15.f];
//    search_textView.textContainer.lineFragmentPadding = 0.0f;
    search_textView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
    [self addSubview:search_textView];
    

    //线条
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(searchView_X - 2, CGRectGetMaxY(imageView.frame) + searchView_X, search_textView.frame.size.width + CGRectGetMaxX(imageView.frame)-5, 1)];
    line.backgroundColor = color;
    [self addSubview:line];
    
    

}


- (UIBarButtonItem *)rithtScanBtn{
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon-QR"] style:UIBarButtonItemStyleDone target:self action:@selector(showQRCode:)];
    return item;

}

#pragma  mark - UITextView Delegete

//将要开始编辑
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    
    if (isClearn == true) {
        isClearn = false;
        textView.text = @"";
    }
    
    [keyboardView removeFromSuperview];
    keyboardView = [UtilToolsClss returnMaskKeyBoardvViewForObj:self orMethod:@selector(clickview:) ];
    [_controller.view addSubview:keyboardView];
    keyboardView.tag = 500;
    [_controller.view bringSubviewToFront:keyboardView];
    [UIView animateWithDuration:0.2 animations:^{
        keyboardView.alpha= 0.3;
    }];
     
    keyboardView.userInteractionEnabled = YES;
    
    return  YES;
}

//将要结束编辑
- (void)textViewDidEndEditing:(UITextView *)textView{
    if (textView.text.length == 0) {
        if (isClearn == false) {
            if ([[NSUD objectForKey:MDC_SET_SEARCHSTATS] intValue] == 1) {
                [NSUD setBool:NO forKey:MDC_SET_SEARCHSTATS]; //搜索状态解除 = 0
            }
             isClearn = true;
             textView.text =@"搜索";
            
           
                if ([self.delegete respondsToSelector:@selector(headSearchDeviceForKeyWord:)]) {
                    NSLog(@"text --->%@",textView.text);
                    [self.delegete headSearchDeviceForKeyWord:textView];
            }
        }
    }
}

//内容发生改变编辑
- (void)textViewDidChange:(UITextView *)textView {
    
   // NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage];//当前的输入模式
    NSArray *ary = [UITextInputMode activeInputModes];
    UITextInputMode * current  = [ary firstObject];
    if ([current.primaryLanguage isEqualToString:@"zh-Hans"])
    {
        //        如果输入有中文，且没有出现文字备选框就对字数统计和限制
        //        出现了备选框就暂不统计
        UITextRange *range = [textView markedTextRange];
        
        UITextPosition *position = [textView positionFromPosition:range.start offset:0];
        
        if (!position)
        {
            [self changeRemoveText:textView];
        }
    }
    else
    {
        [self changeRemoveText:textView];
    }
}


- (void)changeRemoveText:(UITextView *)textview {
    
    if (textview.text.length > 14)
    {
        textview.text = [textview.text substringToIndex:14];
    }

    NSInteger length = textview.text.length;
    NSInteger num = 14 - length;
    num = MAX(num, 0);
    
    NSLog(@"当前长度 =============  %ld",(long)num);
    if (num == 14) {
        isClearn = true;
                [search_textView setText:nil];
                [NSUD setBool:YES forKey:MDC_SET_SEARCHSTATS]; //进入搜索状态 =1
                [self.delegete headSearchDeviceForKeyWord:search_textView];
                [self clickview:nil];
                search_textView.text = @"搜索";
        if ([[NSUD objectForKey:MDC_SET_SEARCHSTATS] intValue] == 1) {
            [NSUD setBool:NO forKey:MDC_SET_SEARCHSTATS]; //搜索状态解除 = 0
        }
    }
}


//内容将要发生改变编辑
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
  //  UITextRange *selectedRange = textView.markedTextRange;
    if ([text isEqualToString:@"\n"] ) {//|| selectedRange == nil || selectedRange.empty
        if ([self.delegete respondsToSelector:@selector(headSearchDeviceForKeyWord:)]) {
            [self clickview:nil];
            [NSUD setBool:YES forKey:MDC_SET_SEARCHSTATS]; //进入搜索状态 =1
            [self.delegete headSearchDeviceForKeyWord:textView];
            
        }
    }
    return YES;
}




#pragma  mark - CtrlCodeScan Delegate
- (void)didCodeScanOk:(id)info {
    NSLog(@"获取到二维码内容：--->%@", info); //https://itunes.apple.com/us/app/oilklenze/id1150966485?l=zh&ls=1&mt=8
    // 判断是否包含以下内容1007167022
    if ([info rangeOfString:@"https://itunes.apple.com/us/app/oilklenze/id1150966485?l=zh&ls=1&mt=8&code="].location != NSNotFound) {
        UIStoryboard* story                        = [UIStoryboard storyboardWithName:@"Main" bundle:NULL];
        
        [[NSUserDefaults standardUserDefaults] setObject:info forKey:@"scanInfo"];
        NSString* infoStr = [NSString stringWithFormat:@"%@", info];
        NSDictionary* parameters = @{ @"deviceQRCode" : [infoStr substringFromIndex:(infoStr.length - 22)] };
        
        [EquipmenDetailsViewModel requestWithUrlForDeviceDetails:_controller andParam:parameters success:^(DeviceDetailsModel *model) {
            if ( model != nil) {
                //???: 这里有个问题：如果快速扫描时，会不弹出详情页面
                SystemInfoController *info  = [story instantiateViewControllerWithIdentifier:@"SystemInfo"];
                info.delegate = (id)_controller;
                info.detailsAry = [NSMutableArray arrayWithObjects:model, nil];
                [_controller presentViewController:info animated:YES completion:nil];
            }
        } failure:^(NSString *error) {
            [MBProgressHUD yty_showErrorWithTitle:nil detailsText:NSLocalizedString(@"HsvaLead_CannotBind",@"无法绑定") toView:nil];
            
            if (([NSUD objectForKey:MDC_SET_MASKVIEW] != nil)) {
                if ([[NSUD objectForKey:MDC_SET_MASKVIEW] isEqualToString:@"加遮"]) {
                    [self didTopBack:nil];
                }
            }
        }];
    }else {
            if (([NSUD objectForKey:MDC_SET_MASKVIEW] != nil)) {
                if ([[NSUD objectForKey:MDC_SET_MASKVIEW] isEqualToString:@"加遮"]) {
                     [self didTopBack:nil];
            }
        }
    }
}

- (void)didTopBack:(id)objs {
    [_controller removeMaskLayer];
    [_controller addCourseListOfDimensionalCodeScanning];
}


// 扫描二维码
- (void)showQRCode:(UIButton *)sende {
    if (TARGET_IPHONE_SIMULATOR) {
        NSLog(@"请使用设备进行测试！");
    }
    else {
        CtrlCodeScan* scan = [[CtrlCodeScan alloc] init];
        scan.delegate = self;
        [_controller presentViewController:scan animated:YES completion:^{
            
        }];
    }
}

// 关闭背景遮罩，与键盘
- (void)clickview:(UITableView *)tap {
    UIView *view = [_controller.view viewWithTag:500];
    [UIView animateWithDuration:0.2 animations:^{
        view.alpha = 0;
    }];
    
    [search_textView endEditing:YES];
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
